package me.zhengjie.modules.business.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.business.service.OfficialService;
import me.zhengjie.modules.business.util.OfficialUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/official", produces = "application/text; charset=utf-8")//解决乱码问题
public class OfficialController {


    public OfficialService officialService;

    public OfficialController(OfficialService officialService) {
        this.officialService = officialService;
    }

    @RequestMapping(method = RequestMethod.POST)
    @AnonymousAccess
    public String handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map<String,String> map = OfficialUtil.parseXml(request);
        System.out.println("----收到消息----");
        System.out.println(map);
        String respStr = officialService.parseMessage(map);
        System.out.println("----返回消息----");
        System.out.println(respStr);
        return respStr;
    }

    /**
     *
     * @description 链接微信公众号平台
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 	随机字符串
     * @return 验证结果 true 成功 false 失败
     * @author churuitao
     * @date 2020年01月27日 19:30
     */
    @RequestMapping(method = RequestMethod.GET)
    @AnonymousAccess
    public String connectionWXServer(@RequestParam("signature") String signature,
                                    @RequestParam("timestamp") String timestamp,
                                    @RequestParam("nonce") String nonce,
                                    @RequestParam("echostr") String echostr){
        boolean b = OfficialUtil.validParams(signature, timestamp, nonce);
        if(b){
            return(echostr);
        }
        return null;
    }

}
